package org.flexthinker.module
{
    import flash.events.Event;

    import mx.events.FlexEvent;

    import mx.events.ModuleEvent;

    import mx.logging.Log;
    import mx.logging.targets.TraceTarget;
    import mx.modules.Module;

    import org.flexthinker.module.ModuleViewLoader;
    import org.flexthinker.module.impl.ModuleDescriptor;
    import org.flexunit.async.Async;
    import org.fluint.uiImpersonation.UIImpersonator;
    import org.hamcrest.assertThat;
    import org.hamcrest.object.equalTo;

    import spark.components.Button;

    public class ModuleViewLoader2Test
    {
        //to be used when tested from IJ IDE
//        private static const MODULE_URL:String = "test-classes/test/ButtonModule.swf";

        // to the used when tested with maven
        private static const MODULE_URL:String = "test/ButtonModule.swf";

        private var loader:ModuleViewLoader;

        private var btn:Button;

        public function ModuleViewLoader2Test()
        {
        }

        [Before(async,ui)]
        public function setUp():void
        {
            loader = new ModuleViewLoader();

            btn = new Button();
            btn.label = "Test";
            btn.x = 300;

            Async.proceedOnEvent(this, loader, FlexEvent.CREATION_COMPLETE, 200);

            UIImpersonator.addChild(loader);
            UIImpersonator.addChild(btn);

            Log.addTarget(new TraceTarget());
        }

        [After(async,ui)]
        public function tearDown():void
        {
            UIImpersonator.removeChild(loader);
            loader = null;
        }

        [Test(async,ui, timeout="4000")]
        public function testLoadingModuleWithoutSkin():void
        {
            loader.url = MODULE_URL;

            assertThat("moduleViewLoader should not have any dependency",
                    ModuleDescriptor(loader.moduleDescriptor).dependencies.length, equalTo(0));

            Async.handleEvent(this, loader, ModuleEvent.READY, moduleWithoutSkin_readyHandler, 2000);

            loader.load();
        }

        public function moduleWithoutSkin_readyHandler(event:ModuleEvent, param:Object):void
        {
            assertThat("not enough bytes loaded", loader.bytesLoaded > 630000, equalTo(true));
            Async.handleEvent(this, loader, Event.COMPLETE, checkStyles2, 1000);
        }

        private function checkStyles2(event:Event, param:Object):void
        {
            var module:Module = Module(loader.getElementAt(0));
            assertThat("module's should have default style applied",
                    module.styleManager.getStyleDeclaration("spark.components.Button").getStyle("color"),
                    equalTo(null));
            loader.unload();
        }
    }
}